let form = layui.form
// 获取分类，熏染
$.ajax({
    url: '/my/category/list',
    success: function (res) {
        let arr = []
        res.data.forEach(item => {
            arr.push(`<option value='${item.id}'>${item.name}</option>`)
        })
        $('select[name=cate_id]').append(arr.join(""))
        // 更新渲染
        form.render('select')
    }
})

// 把textarea插件调用
initEditor()

// 剪裁效果
let image = $('#image')
let option = {
    aspectRatio: 400 / 280,
    preview: '.img-preview'
}
image.cropper(option)

// 点击按钮触发单机事件
$('button:contains("选择封面")').on('click', function () {
    $('#file').trigger('click')
})

// 当文件域内容改变，更换图片
$('#file').on('change', function () {
    let files = this.files
    let url = URL.createObjectURL(files[0])
    image.cropper('destroy').attr('src', url).cropper(option)
})


// 表单提交，阻止默认，收集，ajax
$('form').on('submit', function (e) {
    e.preventDefault()
    let fd = new FormData(this)//传入dom
    // 修改fd里的content
    fd.set('content', tinyMCE.activeEditor.getContent())
    // 剪裁图片
    let canvas = image.cropper('getCroppedCanvas', {
        width: 400,
        height: 280
    })
    canvas.toBlob(function (blob) {
        fd.append('cover_img', blob)
        $.ajax({
            type: 'POST',
            url: '/my/article/add',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                layer.msg(res.message)
                if (res.status === 0) {
                    location.href = './list.html'
                }
            }
        })
    })
})